package com.pms.api;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baidubce.services.tsdb.model.*;
import com.pms.controller.BaseController;
import com.pms.entity.QueryParam;
import com.pms.exception.R;
import com.pms.exception.RRException;
import com.pms.service.tsdb.IIotDeviceService;
import com.pms.service.tsdb.ITsdbService;
import com.pms.utils.TsdbReqParamUtil;
import com.pms.validator.Assert;
import io.swagger.annotations.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.repository.query.Param;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 聚合函数类型{1-求平均数，2-总记录数，3-求总和,4-求相邻值的差,5/6-求最大/小值,7/8-求倍数/除数,9/10-求第一个/最后一个值}
 */
@RestController
@Api(value = "设备模板Api接口", description = "设备模板Api接口")
@RequestMapping(value = "/iotSchema", method = RequestMethod.POST)
public class IotSchemaApi extends BaseController {
    @Autowired
    IIotDeviceService iotDeviceService;
    @ApiOperation(value = "查询设备模板列表")
    @RequestMapping(value = "/readSchemaPage", method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "address", value = "查询地址(1-广州默认，2-北京)", required = false, dataType = "int", paramType = "form"),
            @ApiImplicitParam(name = "key", value = "查询关键字，模板名称", required = false, dataType = "string", paramType = "form"),
            @ApiImplicitParam(name = "order", value = "排序规则(1-asc(默认)/2-desc)", required = false, dataType = "string", paramType = "form"),
            @ApiImplicitParam(name = "orderBy", value = "排序字段(1-name(默认)/2-createTime/3-lastUpdatedTime)", required = false, dataType = "string", paramType = "form"),
            @ApiImplicitParam(name = "pageNo", value = "查询页码，默认1", required = false, dataType = "int", paramType = "form"),
            @ApiImplicitParam(name = "pageSize", value = "查询数量，默认10", required = false, dataType = "int",paramType = "form"),
    })
    public R readSchema(Integer address,String orderBy,String order,String key,Integer pageNo,Integer pageSize) {
        JSONObject paramJson = new JSONObject();
        if(pageNo==null||pageNo<1){pageNo = 1;}
        if(pageSize==null||pageSize<1){pageSize = 10;}
        paramJson.put("pageNo",pageNo);
        paramJson.put("pageSize",pageSize);
        if(StringUtils.isNotBlank(key)){
            paramJson.put("key",key);
        }
        if(StringUtils.isNotBlank(order)){
            if(order.equals("1")||order.equals("asc")||order.equals("ASC")){
                order = "asc";
            }else if(order.equals("2")||order.equals("desc")||order.equals("DESC")){
                order = "desc";
            }else{
                order = "asc";
            }
            paramJson.put("order",order);
        }
        if(StringUtils.isNotBlank(orderBy)){
            if(orderBy.equals("name")||orderBy.equals("1")){
                orderBy = "name";
            }else if(orderBy.equals("createTime")||orderBy.equals("2")){
                orderBy = "createTime";
            }else if(orderBy.equals("lastUpdatedTime")||orderBy.equals("3")){
                orderBy = "lastUpdatedTime";
            } else{
                orderBy = "name";
            }
            paramJson.put("orderBy",orderBy);
        }
        JSONObject dataJson = iotDeviceService.readSchema( address,paramJson);
        return R.ok().put("code",dataJson.get("iotHttpCode")).put("data", dataJson);
    }
    @ApiOperation(value = "查询设备模板详情")
    @RequestMapping(value = "/readSchemaDetail", method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "address", value = "查询地址(1-广州默认，2-北京)", required = false, dataType = "int", paramType = "form"),
            @ApiImplicitParam(name = "schemaId", value = "设备模板id", required = false, dataType = "string", paramType = "form"),
    })
    public R readSchemaDetail(Integer address,String schemaId) {
        if(StringUtils.isBlank(schemaId)){
            return R.error(400,"设备模板id不能为空");
        }
        JSONObject dataJson = iotDeviceService.readSchemaDetail(address,schemaId);
        return R.ok().put("code",dataJson.get("iotHttpCode")).put("data", dataJson);
    }

    @ApiOperation(value = "创建设备模板")
    @RequestMapping(value = "/createSchema", method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "address", value = "查询地址(1-广州默认，2-北京)", required = false, dataType = "int", paramType = "form"),
            @ApiImplicitParam(name = "name", value = "设备模板名称", required = true, dataType = "string", paramType = "form"),
            @ApiImplicitParam(name = "description", value = "设备模板描述", required = false, dataType = "string", paramType = "form"),
            @ApiImplicitParam(name = "propertyName", value = "设备模板属性名称,多个属性以,分开", required = true, dataType = "string", paramType = "form"),
            @ApiImplicitParam(name = "propertyType", value = "设备模板属性类型,多个属性以,分开(1-string,2-number,3-bool,4-JSONObject)", required = true, dataType = "string", paramType = "form"),
            @ApiImplicitParam(name = "propertyDisplayName", value = "设备模板属性显示名称,多个属性以,分开", required = true, dataType = "string", paramType = "form"),
            @ApiImplicitParam(name = "propertyDefaultValue", value = "设备模板属性默认值,多个属性以,分开", required = true, dataType = "string", paramType = "form"),
            @ApiImplicitParam(name = "propertyUnit", value = "设备模板属性单位,多个属性以,多个属性以,分开", required = true, dataType = "string", paramType = "form"),
    })
    public R createSchema(Integer address,String name, String description,String propertyName,String propertyType
            ,String propertyDisplayName,String propertyDefaultValue,String propertyUnit) {
        Assert.parameterIsBlank(name,"设备模板名称不能为空");
        Assert.parameterIsBlank(propertyName,"设备模板属性名称不能为空");
        Assert.parameterIsBlank(propertyType,"设备模板属性类型不能为空");
        Assert.parameterIsBlank(propertyDisplayName,"设备模板属性显示名称不能为空");
        Assert.parameterIsBlank(propertyDefaultValue,"设备模板属性默认值不能为空");
        Assert.parameterIsBlank(propertyUnit,"设备模板属性单位不能为空");
        String[] propertyNameArr = propertyName.split(",");
        String[] propertyTypeArr = propertyType.split(",");
        String[] propertyDisplayNameArr = propertyDisplayName.split(",");
        String[] propertyDefaultValueArr = propertyDefaultValue.split(",");
        String[] propertyUnitArr = propertyUnit.split(",");
        JSONObject paramJSONO = new JSONObject();
        paramJSONO.put("name",name);
        if(StringUtils.isBlank(description)){
            description ="";
        }
        paramJSONO.put("description",description);
        JSONArray properties = new JSONArray();
        if(propertyNameArr.length==propertyTypeArr.length && propertyNameArr.length==propertyDisplayNameArr.length
                &&propertyNameArr.length==propertyDefaultValueArr.length && propertyNameArr.length==propertyUnitArr.length){
            for(int x=0;x<propertyNameArr.length;x++){
                Assert.parameterIsBlank(propertyNameArr[x],"设备模板属性名称不能为空");
                Assert.parameterIsBlank(propertyTypeArr[x],"设备模板属性类型不能为空");
                Assert.parameterIsBlank(propertyDisplayNameArr[x],"设备模板属性显示名称不能为空");
                Assert.parameterIsBlank(propertyDefaultValueArr[x],"设备模板属性默认值不能为空");
                Assert.parameterIsBlank(propertyUnitArr[x],"设备模板属性单位不能为空");
                JSONObject property = new JSONObject();
                property.put("name",propertyNameArr[x].trim());
                property.put("type",FormatSchemaPropertyType(propertyTypeArr[x]));
                property.put("displayName",propertyDisplayNameArr[x].trim());
                property.put("defaultValue",propertyDefaultValueArr[x].trim());
                property.put("unit",propertyUnitArr[x].trim());
                properties.add(property);
            }
        }else{
            return  R.error(400,"设备模板属性参数错误,数组长度出错");
        }
        paramJSONO.put("properties",properties);
        JSONObject dataJson = iotDeviceService.createSchema(address,paramJSONO);
        return R.ok().put("code",dataJson.get("iotHttpCode")).put("data", dataJson);
    }

    @ApiOperation(value = "更新设备模板")
    @RequestMapping(value = "/editSchema", method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "address", value = "查询地址(1-广州默认，2-北京)", required = false, dataType = "int", paramType = "form"),
            @ApiImplicitParam(name = "schemaId", value = "设备模板id", required = true, dataType = "string", paramType = "form"),
//            @ApiImplicitParam(name = "name", value = "设备模板名称", required = true, dataType = "string", paramType = "form"),
            @ApiImplicitParam(name = "description", value = "设备模板描述", required = false, dataType = "string", paramType = "form"),
            @ApiImplicitParam(name = "propertyName", value = "设备模板属性名称,多个属性以,分开", required = true, dataType = "string", paramType = "form"),
            @ApiImplicitParam(name = "propertyType", value = "设备模板属性类型,多个属性以,分开(1-string,2-number,3-bool,4-JSONObject)", required = true, dataType = "string", paramType = "form"),
            @ApiImplicitParam(name = "propertyDisplayName", value = "设备模板属性显示名称,多个属性以,分开", required = true, dataType = "string", paramType = "form"),
            @ApiImplicitParam(name = "propertyDefaultValue", value = "设备模板属性默认值,多个属性以,分开", required = true, dataType = "string", paramType = "form"),
            @ApiImplicitParam(name = "propertyUnit", value = "设备模板属性单位,多个属性以,多个属性以,分开", required = true, dataType = "string", paramType = "form"),
    })
    public R editSchema(Integer address,String schemaId,String description,String propertyName,String propertyType
            ,String propertyDisplayName,String propertyDefaultValue,String propertyUnit) {
        Assert.parameterIsBlank(schemaId,"设备模板id不能为空");
//        Assert.parameterIsBlank(name,"设备模板名称不能为空");
        JSONObject paramJSONO = new JSONObject();
//        paramJSONO.put("name",name);
        if(description!=null){
            if(StringUtils.isBlank(description)){
                description ="";
            }
            paramJSONO.put("description",description);
        }

        if(StringUtils.isNotBlank(propertyName)){
            Assert.parameterIsBlank(propertyType,"设备模板属性类型不能为空");
            Assert.parameterIsBlank(propertyDisplayName,"设备模板属性显示名称不能为空");
            Assert.parameterIsBlank(propertyDefaultValue,"设备模板属性默认值不能为空");
            Assert.parameterIsBlank(propertyUnit,"设备模板属性单位不能为空");
//            Assert.parameterIsEmpty(propertyName,"设备模板属性名称不能为空");
            List<String> propertyNameList = Arrays.asList(propertyName.split(","));
            List<String> propertyTypeList = Arrays.asList(propertyType.split(","));
            List<String> propertyDisplayNameList = Arrays.asList(propertyDisplayName.split(","));
            List<String> propertyDefaultValueList = Arrays.asList(propertyDefaultValue.split(","));
            List<String> propertyUnitList = Arrays.asList(propertyUnit.split(","));
            JSONArray properties = new JSONArray();
            if(propertyNameList.size()==propertyTypeList.size() &&propertyNameList.size()==propertyUnitList.size()
                    &&propertyNameList.size()==propertyDisplayNameList.size()&&propertyNameList.size()==propertyDefaultValueList.size() ){
                for(int x=0;x<propertyNameList.size();x++){
                    Assert.parameterIsBlank(propertyNameList.get(x),"设备模板属性名称不能为空");
                    Assert.parameterIsBlank(propertyTypeList.get(x),"设备模板属性类型不能为空");
                    Assert.parameterIsBlank(propertyDisplayNameList.get(x),"设备模板属性显示名称不能为空");
                    Assert.parameterIsBlank(propertyDefaultValueList.get(x),"设备模板属性默认值不能为空");
                    Assert.parameterIsBlank(propertyUnitList.get(x),"设备模板属性单位不能为空");
                    JSONObject property = new JSONObject();
                    property.put("name",propertyNameList.get(x).trim());
                    property.put("type",FormatSchemaPropertyType(propertyTypeList.get(x)));
                    property.put("displayName",propertyDisplayNameList.get(x).trim());
                    property.put("defaultValue",propertyDefaultValueList.get(x).trim());
                    property.put("unit",propertyUnitList.get(x).trim());
                    properties.add(property);
                }
            }else{
                return  R.error(400,"设备模板属性参数错误,数组长度出错");
            }
            paramJSONO.put("properties",properties);
        }
        JSONObject dataJson = iotDeviceService.editSchema(address,schemaId,paramJSONO);
        return R.ok().put("code",dataJson.get("iotHttpCode")).put("data", dataJson);
    }
    @ApiOperation(value = "删除设备模板")
    @RequestMapping(value = "/delSchema", method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "address", value = "查询地址(1-广州默认，2-北京)", required = false, dataType = "int", paramType = "form"),
            @ApiImplicitParam(name = "schemaId", value = "设备模板id", required = false, dataType = "string", paramType = "form"),
    })
    public R delSchema(Integer address,String schemaId) {
        if(StringUtils.isBlank(schemaId)){
            return R.error(400,"设备模板id不能为空");
        }
        JSONObject dataJson = iotDeviceService.delSchema(address,schemaId);
        return R.ok().put("code",dataJson.get("iotHttpCode")).put("data", dataJson);
    }

    public String FormatSchemaPropertyType(String param_type){
        param_type= param_type.trim();
        if(param_type.equals("1")||param_type.equals("string")||param_type.equals("String")){
            return "string";
        }
        if(param_type.equals("2")||param_type.equals("number")){
            return "number";
        }
        if(param_type.equals("3")||param_type.equals("bool")){
            return "bool";
        }
        if(param_type.equals("4")||param_type.equals("object")||param_type.equals("obj")||param_type.equals("JSONObject")){
            return "object";
        }
        return "number";
    }


}
